<template>
  <Teleport to="body">
    <Transition name="fade">
      <div v-if="show" ref="target" class="context-menu" :style="{ inset: `${position.y}px auto auto ${position.x}px` }">
        <ul class="context-menu-list">
          <li class="context-menu-item" v-for="item in props.menu" :key="item.key" @click="clickContextMenu(item)">
            <el-icon>
              <i-ep-Edit v-if="item.key === 'edit'" />
              <i-ep-Delete v-else-if="item.key === 'delete'" />
            </el-icon>
            <span>{{ item.name }}</span>
          </li>
        </ul>
      </div>
    </Transition>
  </Teleport>
</template>

<script setup lang="ts">
/**
 * 右键菜单组件
 */
import { ref } from "vue";
import { onClickOutside, useVModel } from "@vueuse/core";

interface Menu {
  key: string;
  name: string;
  icon: string;
}
interface Position {
  x: number;
  y: number;
}
interface Props {
  visible: boolean;
  menu: Menu[];
  position: Position;
}
const props = withDefaults(defineProps<Props>(), {
  visible: false,
  menu: () => [],
  position: () => {
    return { x: 0, y: 0 };
  }
});
const emit = defineEmits(["update:visible", "clickContextMenu"]);

const show = useVModel(props, "visible", emit);

const target = ref(null);

// 点击非本组件元素时，本组件不显示
onClickOutside(target, () => {
  show.value = false;
});

// 处理点击事件
const clickContextMenu = (e: Menu) => {
  emit("clickContextMenu", e.key);
};
</script>

<style lang="scss" scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
.context-menu {
  position: absolute;
  // inset: 100px auto auto 100px;
  box-sizing: border-box;
  z-index: 999;
  font-size: var(--el-font-size-small);
  color: var(--el-text-color-primary);
  &-list {
    padding: 4px;
    list-style-type: none;
    background-color: var(--el-bg-color);
    background-clip: padding-box;
    border-radius: 8px;
    outline: none;
    background: var(--el-bg-color-overlay);
    border: 1px solid var(--el-border-color-light);
    box-shadow: var(--el-box-shadow-light);
  }
  &-item {
    clear: both;
    padding: 5px 12px;
    cursor: pointer;
    transition: all 0.2s;
    border-radius: 4px;
    display: flex;
    align-items: center;
    .el-icon {
      margin-right: 5px;
    }
    &:hover {
      background-color: var(--el-color-primary-light-9);
      color: var(--el-color-primary);
    }
  }
}
</style>
